package com.joe.security.distributed.auth.dao;

import com.joe.security.distributed.auth.model.PermissionDto;
import com.joe.security.distributed.auth.model.UserDto;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author 高建伟-joe
 * @Date 2023-11-09
 */
@Repository
public class UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据用户名 查询用户信息
     * @param username
     * @return
     */
    public UserDto getUserByUsername(String username){
        String sql = "select id, username, password, fullname, mobile from user where username = ?";
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    /**
     * 根据用户id 查询用户权限
     * @param userId
     * @return
     */
    public List<String> getPermissionByUserId(String userId){
        String sql = "SELECT \n" +
                " p.* \n" +
                "FROM permission p\n" +
                "INNER JOIN role_permission rp ON p.id = rp.permission_id\n" +
                "INNER JOIN user_role ur ON rp.role_id = ur.role_id\n" +
                "WHERE ur.user_id = ?";
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        if (CollectionUtils.isEmpty(list)){
            return null;
        }

        List<String> permissionList = new ArrayList<>();
        list.forEach(e->permissionList.add(e.getCode()));
        return permissionList;
    }
}
